﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using DataAccess;
using Model;
using Model.EntityModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for RegisterComplaintPart2.xaml
    /// </summary>
    public partial class RegisterComplaintPart2 : UserControl
    {
        public long ComplaintId { get; set; }

        private List<FunctionaryInfo> EmployeesToAdd ;
        public RegisterComplaintContent RegContentPrev { get; set; }

        public RegisterComplaintPart2(RegisterComplaintContent regContentPrev)
        {
            InitializeComponent();
            RegContentPrev = regContentPrev;
            lblCaseNumber.Content = RegContentPrev.lblCaseNumber.Content;
            ComplaintId = long.Parse(lblCaseNumber.Content.ToString());
            lblRegistrationDate.Content = RegContentPrev.lblRegistrationDate.Content;
            tbIncidentDetail.AddValitationRule(new ShortStringRule(50));
            tbEvidenceDescription.AddValitationRule(new ShortStringRule(15));
            gridAddEvidence.Height = 0;
            EmployeesToAdd = new List<FunctionaryInfo>();
            listBoxIntervinents.DataContext = EmployeesToAdd;
        }

        private void btnAddEvidence_Click(object sender, RoutedEventArgs e)
        {
            ShowDialogGrid();
            lblEvidenceNumber.Content = listBoxEvidences.Items.Count + 1;
            if (string.IsNullOrEmpty(tbEvidenceDescription.Text))
                lblEvidenceERROR.Visibility = Visibility.Hidden;
            else
            {
                tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
                if (tbEvidenceDescription.Text.Length >= 15)
                    lblEvidenceERROR.Visibility = Visibility.Hidden;
                else
                {
                    lblEvidenceERROR.Visibility = Visibility.Visible;
                }
            }
        }

        private void ShowDialogGrid()
        {
            btnAddEvidence.IsHitTestVisible = false;
            tbEvidenceDescription.IsHitTestVisible = true;
            DoubleAnimation doubleAnimation = new DoubleAnimation(0, 196, new Duration(new TimeSpan(0, 0, 0, 0, 500)));
            Storyboard st = new Storyboard();
            st.Children.Add(doubleAnimation);
            Storyboard.SetTargetProperty(st, new PropertyPath("Height"));
            Storyboard.SetTargetName(st, "gridAddEvidence");
            BeginStoryboard(st);
        }

        private void HideDialogGrid()
        {
            btnAddEvidence.IsHitTestVisible = true;
            tbEvidenceDescription.IsHitTestVisible = false;
            DoubleAnimation doubleAnimation = new DoubleAnimation(196, 0, new Duration(new TimeSpan(0, 0, 0, 0, 500)));
            Storyboard st = new Storyboard();
            st.Children.Add(doubleAnimation);
            Storyboard.SetTargetProperty(st, new PropertyPath("Height"));
            Storyboard.SetTargetName(st, "gridAddEvidence");
            BeginStoryboard(st);
        }

        private void btnAddCancel_Click(object sender, RoutedEventArgs e)
        {
            HideDialogGrid();
            Validation.ClearInvalid(tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty));
            if (tbEvidenceDescription.Text.Length >= 15)
                lblEvidenceERROR.Visibility = Visibility.Hidden;
        }

        private void btnAddSuccess_Click(object sender, RoutedEventArgs e)
        {
            tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            bool hasError = Validation.GetHasError(tbEvidenceDescription);
            if (!hasError)
            {
                listBoxEvidences.Items.Add(new Evidence
                                               {
                                                   IdComplaint = ComplaintId,
                                                   Number = int.Parse(lblEvidenceNumber.Content.ToString()),
                                                   Description = tbEvidenceDescription.Text
                                               });
                listBoxEvidences.UpdateLayout();
                HideDialogGrid();
                tbEvidenceDescription.Text = "";
                Validation.ClearInvalid(tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty));
                lblEvidenceERROR.Visibility = Visibility.Hidden;
                lblEvidencesError.Visibility = Visibility.Hidden;
            }
            else
            {
                lblEvidenceERROR.Visibility = Visibility.Visible;
            }
        }


        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var style = new Style(typeof (Xceed.Wpf.Toolkit.MessageBox));
            style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty,"Si"));
            var res = Xceed.Wpf.Toolkit.MessageBox.Show("Esta seguro(a) de que desea eliminar la evidencia de la lista?", "Confirmar Accion!",MessageBoxButton.YesNo,MessageBoxImage.Warning,style);
            if (res == MessageBoxResult.Yes)
            {
                Button cmd = (Button) sender;
                if (cmd.DataContext is Evidence)
                {
                    Evidence deleteme = (Evidence) cmd.DataContext;
                    listBoxEvidences.Items.Remove(deleteme);
                    int i = 1;
                    foreach (var lbItem in listBoxEvidences.Items)
                    {
                        if (lbItem is Evidence)
                        {
                            (lbItem as Evidence).Number = i;
                            i++;
                        }
                    }
                    listBoxEvidences.UpdateLayout();
                }
            }
        }

        private void btnAddIntervinent_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.allEmployees.Clear();
            searchFunctionary.employeesToShow = searchFunctionary.employeesToShow.Where(x => !EmployeesToAdd.Any(x1 => x1.CI == x.CI))
            .Union(EmployeesToAdd.Where(x => !searchFunctionary.employeesToShow.Any(x1 => x1.CI == x.CI))).ToList();
            searchFunctionary.listViewEmployees.DataContext = searchFunctionary.employeesToShow;
            searchFunctionary.listViewEmployees.Items.Refresh();
            searchFunctionary.listViewEmployees.MouseDoubleClick += EmployeeAdded;
            searchFunctionary.ShowDialog();
        }

        private void EmployeeAdded(object sender, MouseButtonEventArgs e)
        {
            var listbox = sender as ListBox;
            EmployeesToAdd.Add((listbox.SelectedValue as FunctionaryInfo));
            listBoxIntervinents.Items.Refresh();
            listBoxIntervinents.UpdateLayout();
            lblIntervinentsError.Visibility = Visibility.Hidden;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var style = new Style(typeof(Xceed.Wpf.Toolkit.MessageBox));
            style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
            var res = Xceed.Wpf.Toolkit.MessageBox.Show("Esta seguro(a) de que desea eliminar a la funcionaria de la lista?", "Confirmar Accion!", MessageBoxButton.YesNo, MessageBoxImage.Warning, style);
            if (res == MessageBoxResult.Yes)
            {
                Button cmd = (Button)sender;
                if (cmd.DataContext is FunctionaryInfo)
                {
                    FunctionaryInfo deleteme = (FunctionaryInfo)cmd.DataContext;
                    EmployeesToAdd.Remove(deleteme);
                    listBoxIntervinents.Items.Refresh();
                    listBoxEvidences.UpdateLayout();
                }
            }
        }

        private void btnSelectRecepter_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var recepterFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (recepterFuncionary != null)
            {
                lblRecepterName.Content = recepterFuncionary.Name;
                lblRecepterCi.Content = recepterFuncionary.CI;
                RecepterInfo.Visibility = Visibility.Visible;
                lblRecepterError.Visibility = Visibility.Hidden;
            }
        }

        private void btnSelectAsigned_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var asignedFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (asignedFuncionary != null)
            {
                lblAsignedName.Content = asignedFuncionary.Name;
                lblAsignedCi.Content = asignedFuncionary.CI;
                AsignedInfo.Visibility = Visibility.Visible; 
                lblAsignedError.Visibility = Visibility.Hidden;
            }
        }

        private void btnSelectSecBoss_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var secBossFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (secBossFuncionary != null)
            {
                lblSecBossName.Content = secBossFuncionary.Name;
                lblSecBossCi.Content = secBossFuncionary.CI;
                SecurityBossInfo.Visibility = Visibility.Visible;
                lblSecBossError.Visibility = Visibility.Hidden;
            }
        }

        private void SaveAndContinue_Click(object sender, RoutedEventArgs e)
        {
            RegContentPrev.regPart2 = this;
            var par = this.Parent as ItemsControl;
            par.Items.Clear();
            par.Items.Add(RegContentPrev);
        }


        public List<Evidence> GatherEvidences()
        {
            List<Evidence> evidences = new List<Evidence>();
            foreach (var item in listBoxEvidences.Items)
            {
                evidences.Add(item as Evidence);
            }
            return evidences;
        }

        public List<FunctionaryInfo> GatherIntervinents()
        {
            List<FunctionaryInfo> intervinents = new List<FunctionaryInfo>();
            foreach (var item in listBoxIntervinents.Items)
            {
                intervinents.Add(item as FunctionaryInfo);
            }
            return intervinents;
        }

        private void SaveComplaint()
        {
            try
            {
                bool hasErrors = CheckHasErrors();
                if (!hasErrors)
                {
                    RegContentPrev.SaveFirstPartOfComplaint(tbIncidentDetail.Text);
                    var evidences = GatherEvidences();
                    foreach (var evidence in evidences)
                    {
                        ComplaintDataAccess.InsertEvidence(evidence);
                    }
                    var intervinents = GatherIntervinents();
                    foreach (var interv in intervinents)
                    {
                        ComplaintDataAccess.InsertEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = interv.CI ,IdComplaint = ComplaintId, Responsability = "Interviniente"});
                    }
                    ComplaintDataAccess.InsertEmployeeOfComplaint(new EmployeeOfComplaint  {CIEmployee = long.Parse(lblRecepterCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Recepcionista"});
                    ComplaintDataAccess.InsertEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = long.Parse(lblAsignedCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Asignada" });
                    ComplaintDataAccess.InsertEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = long.Parse(lblSecBossCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Jefe de Seguridad" });
                    var style = new Style(typeof(Xceed.Wpf.Toolkit.MessageBox));
                    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
                    var resB = Xceed.Wpf.Toolkit.MessageBox.Show("La denuncia se registró exitosamente, tome nota, el numero de Denuncia es: "+lblCaseNumber.Content+". Desea imprimir la denuncia?",
                                                                "Exito!", MessageBoxButton.YesNo,
                                                                MessageBoxImage.Information, style);
                    if (resB == MessageBoxResult.Yes)
                    {
                        var items = new ObservableCollection<UserControl>();
                        items.Add(new PrintComplaint(ComplaintId));
                        items.Add(new PrintComplaintPart2(ComplaintId));
                        items.Add(new PrintComplaintPart3(ComplaintId));
                        var a = new PrintPreviewDialogV2(items);    
                        a.ShowDialog();
                    }
                    else
                    {
                        Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la denuncia posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Denuncia",
                                                                "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    UIWindowManager.CleanWindow(this);
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Se deben llenar todos los campos indicados para poder continuar!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (UpdateException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (EntitySqlException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (SqlException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error desconocido, no se modifico la denuncia!", "Error!");
            }
        }

        private bool CheckHasErrors()
        {
            bool res = false;
            tbIncidentDetail.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            if (Validation.GetHasError(tbIncidentDetail))
                res = true;
            if (listBoxEvidences.Items.Count == 0)
            {
                lblEvidencesError.Visibility = Visibility.Visible;
                res = true;
            }
            if (listBoxIntervinents.Items.Count == 0)
            {
                lblIntervinentsError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblRecepterName.Content.ToString()))
            {
                lblRecepterError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblAsignedName.Content.ToString()))
            {
                lblAsignedError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblSecBossName.Content.ToString()))
            {
                lblSecBossError.Visibility = Visibility.Visible;
                res = true;
            }
            return res;
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            SaveComplaint();
        }
    }
}